const fs = require('fs'); 
const path = require("path")
const { app } = require("electron");
const http = require("http");
const Router = require('koa-router') 
const router = new Router()
const schedule =  require('node-schedule') 
const request = require("request");

var all = { url:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=08824ffb-4aaa-4258-b720-ecb78fec64f7",stocks:"",infos:"",  stockMap:{ "sz000610":1 }, recordMap:{}}
let filepath = path.join( app.getPath("userData") ,'copy-stock.json'); 
if (fs.existsSync(filepath)) all = JSON.parse(fs.readFileSync(filepath));

function make() {
    /* 拼接信息 */ 
    var content = ``; 
    var map = all.stockMap;
    for (var key in map) {  
      content += `${map[key][1]}: ${map[key][2]} , ${map[key][3]} ,  ${map[key][4]} ~ ${map[key][5]} ,${map[key][6]}\n`;
    } 
    /* 发送报告 */
    request({
        url: all.url,
        method: "POST",
        json: true,
        headers: { "content-type": "application/json",}, 
        body: { msgtype: "text", text: { content } },
      },
      function (error, response, body) {
        if (!error && response.statusCode == 200) {
          console.log(body); // 请求成功的处理逻辑
        }
      }
    );
  }
  
  function summary() {
    if(/6|0/.test(new Date().getDay())) return;
    var url = `http://qt.gtimg.cn/q=` + Object.keys(all.stockMap).join();
    http.get(url, (res) => { 
      let rawData = "";
      res.on("data", (chunk) => {
        rawData += chunk;
      });
      res.on("end", () => {
        try {
          console.log(rawData); //输出数据 1 股票 3 现价
          var tmp = rawData.split(";\n");
          for (var i = 0; i < tmp.length; i++) {
            var cur = tmp[i].split("~");
            var code = tmp[i].split("=")[0].replace("v_", "");
            if (code) {
              var text = (cur[33] - cur[34]).toFixed(3);
              var x = text / 2;
              var price = parseFloat(cur[3]);
              var arg = 0; 
              if (all.recordMap[code]) {
                all.recordMap[code].push(text);
                arg = (eval(all.recordMap[code].join("+"))) / all.recordMap[code].length
              } else {
                all.recordMap[code] = [text];
                arg = parseFloat(text)
              }
              all.stockMap[code] = [
                cur[1],
                code,
                price,
                text,
                parseFloat(price - x).toFixed(3),
                parseFloat(price + x).toFixed(3),
                arg,
              ];
            }
          }
          make();
        } catch (e) {
          console.error(e.message);
        }
      });
    });
  }
  
  function runner() {
    schedule.scheduleJob("someid", "0 0 16 * * *", function () {
      console.log("run stock summary !");
      summary();
    });
  }
  runner()
  //summary()
  router.all("/api/task", async function (ctx, next) {
    let { runner } = ctx.request.body;
    if(runner){
      runner();
    }else{
      schedule.cancelJob("someid");
    }
    ctx.body = { data: "OK" };
  });
  

  router.all("/api/stock", async function (ctx, next) {
    let { stockMap,url } = ctx.request.body;
    if(stockMap){
        all.url = url || all.url 
        all.stockMap = stockMap;
    }else{
      fs.writeFileSync(filepath, JSON.stringify(all));
    }
    ctx.body = { data: all };
  });

  router.all("/api/stocks", async function (ctx, next) {
    let { stocks,info } = ctx.request.body;
    if(stocks||info){
        all.info = info || all.info 
        all.stocks = stocks || all.stocks 
    }else{
      fs.writeFileSync(filepath, JSON.stringify(all));
    }
    ctx.body = { all };
  });

module.exports = router
 